package com.bizihang.security.browser.config;

import com.bizihang.security.core.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/15
 */
@Slf4j
@Component
public class BrowserAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Autowired
	ObjectMapper objectMapper;

	@Autowired
	SecurityProperties securityProperties;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		log.info("登陆成功");
		switch (securityProperties.getBrowser().getLoginType()) {
			case REDIRECT:
				super.onAuthenticationSuccess(request, response, authentication);
				break;
			default: {
				response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
				response.getWriter().write(objectMapper.writeValueAsString(authentication));
			}
		}
	}
}
